package com.kotlin.zds.web

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.net.http.SslError
import android.os.Build
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.webkit.*
import android.widget.TextView
import androidx.core.view.ViewCompat
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.kotlin.zds.R
import com.kotlin.zds.arouter.Routes
import com.kotlin.zds.base.BaseActivity
import com.kotlin.zds.databinding.ActivityWebViewBinding
import com.zds.support.dialog.CommonDialog
import com.zds.support.extensions.gone
import com.zds.support.extensions.visible
import com.zds.support.manager.UserDataManager
import com.zds.support.rxbus.RxBus
import com.zds.support.rxbus.registerInBus
import com.zds.support.util.*
import com.zds.support.widget.EasyWebView

import io.reactivex.android.schedulers.AndroidSchedulers
import java.util.*

/**
 *
 *@Description 用法 WebViewActivity.startActivity(mActivity,"http://www.baidu.com")
 *@Author zc
 *@Version V1.0
 **/
@Route(path = Routes.PATH_WEB)
class WebViewActivity : BaseActivity() ,JsCallBackInterface{

    private val headMap = HashMap<String, String>()
    private var title: String = ""
    @Autowired(name = "url")
    @JvmField
    var url: String = ""
    private var backgroundColor = 0
    private var titleTextColor = Color.WHITE
    private var webviewJavascriptInterface: WebviewJavascriptInterface? = null
    private var isError = false
    private var isEnableSetTitle = true

    private val viewBinding by lazy {
        ActivityWebViewBinding.inflate(LayoutInflater.from(mActivity))
    }


    companion object {
        fun startActivity(activity: Activity, url: String, title: String? = null) {
            if (TextUtils.isEmpty(url)) {
                return
            } else {
                val intent = Intent(activity, WebViewActivity::class.java)
                intent.putExtra("url", url)
                if (title != null) {
                    intent.putExtra("title", title)
                }
                activity.startActivity(intent)
            }
        }
    }

    override fun onSetContentView() {
        com.xuexiang.xui.utils.StatusBarUtils.initStatusBarStyle(this,false)
        setContentView(viewBinding.root)
    }

    @SuppressLint("JavascriptInterface")
    override fun initView() {
        //获取链接
        val urlFinal = intent.getStringExtra("url")
        if (TextUtils.isEmpty(urlFinal)) {
            finish()
            return
        }
        val titleFinal = intent.getStringExtra("title")
        if (titleFinal != null) {
            isEnableSetTitle = false
            title = titleFinal
            setTitle(title)
        }
        url = urlFinal!!

        headMap["token"] = UserDataManager.instance.getToken()
        headMap["version"] = AppUtils.getVersionName();
        headMap["device_info"] = "${Build.BRAND} ${Build.MODEL} ${Build.VERSION.RELEASE}"

        val webSettings = viewBinding.webView.settings
        webSettings.loadWithOverviewMode = true
        webSettings.allowFileAccess = true
        webSettings.domStorageEnabled = true
        webSettings.allowContentAccess = true
        //跨域
        webSettings.setAllowFileAccessFromFileURLs(true)
        webSettings.setAppCacheEnabled(false)
        webSettings.databaseEnabled = true
        webSettings.cacheMode = WebSettings.LOAD_DEFAULT;
        //设置WebView属性，能够执行Javascript脚本
        webSettings.javaScriptEnabled = true
        //支持自动播放音乐
        webSettings.mediaPlaybackRequiresUserGesture
        webSettings.mediaPlaybackRequiresUserGesture = false

        webviewJavascriptInterface = WebviewJavascriptInterface(mActivity, viewBinding.webView)
        viewBinding.webView.addJavascriptInterface(webviewJavascriptInterface!!, "appJS")

        viewBinding.webView.setWebViewClient(object : WebViewClient() {
            override fun onReceivedSslError(p0: WebView?, sslErrorHandler: SslErrorHandler?, p2: SslError?) {
                val dialog  = CommonDialog.Builder(mActivity)
                        .setMessage("SSL证书错误，是否继续？")
                        .setButtonText("继续","取消")
                        .setOnClickListener { dialog, isPositive ->
                            if (isPositive){
                                sslErrorHandler?.proceed()
                            }else{
                                sslErrorHandler?.cancel()
                            }
                        }
                        .create()
                try {
                    dialog.show()
                }catch (e:Exception){
                    sslErrorHandler?.cancel()
                }
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                if (!isError) {
                    hideErrorNotice()
                }
            }

            override fun onReceivedError(view: WebView?, errorCode: Int, description: String?, failingUrl: String?) {
                super.onReceivedError(view, errorCode, description, failingUrl)
                if (view != null && TextUtils.equals(view.url, failingUrl)) {
                    isError = true
                    showErrorNotice()
                }
            }

            override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
                super.onReceivedError(view, request, error)
                if (request != null && request.isForMainFrame) {
                    isError = true
                    showErrorNotice()
                }
            }
        })
        viewBinding.webView.setWebChromeClient(object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView?, receivedTitle: String?) {
                super.onReceivedTitle(view, receivedTitle)
                if (isEnableSetTitle) {
                    if (receivedTitle == null) {
                        setTitle("")
                    } else {
                        if (view != null && TextUtils.equals(view.url, receivedTitle)) {
                            setTitle("")
                        } else {
                            setTitle(receivedTitle)
                        }
                    }
                }
            }

            override fun onProgressChanged(view: WebView?, progress: Int) {
                super.onProgressChanged(view, progress)
                viewBinding.pb.setProgress(progress)
                if (progress >= 96) {

                    viewBinding.pb.visibility = View.GONE
                } else {
                    viewBinding.pb.visibility = View.VISIBLE
                }
            }

            override fun onConsoleMessage(msg: ConsoleMessage?): Boolean {
                if (msg != null) {
                    Log.d("onConsoleMessage", msg.message())
                }
                return super.onConsoleMessage(msg)

            }
        });
        LogUtils.d("网址", url)
        viewBinding.webView.loadUrl(url, headMap)

        RxBus.observe<WebViewEvent>().registerInBus({ event: WebViewEvent ->
            try {
                when (event.type) {
                    //右侧标题栏文字
                    1 -> {
                        viewBinding.btnMore.visibility = View.VISIBLE

                        if (event.value == "0") {
                            viewBinding.btnMore.visibility = View.GONE
                        } else {
                            viewBinding.tvRightText.text = event.value
                        }

                    }
                    //选择图片数量
                    //  2 -> photoNum = event.value.toInt()
                    //标题栏渐变颜色
                    3 -> {
                        backgroundColor = Color.parseColor(event.value)
                    }
                    //右侧图标
                    4 -> {
                        viewBinding.btnShare.visibility = View.VISIBLE
                        if (event.value == "0") {
                            viewBinding.btnShare.visibility = View.GONE
                        } else {
                            viewBinding.ivRight.loadImage(event.value)
                        }
                    }
                    //设置选择图片类型
                    5 -> {
                        // selectType = event.value.toInt()
                    }
                    // 显示或者隐藏标题栏
                    6 -> {
                        if (TextUtils.equals(event.value, "show")) {
                            val isTranslucent = url.contains("translucent")
                            if (isTranslucent) {
                                viewBinding.layoutActionBarTranslucent.visibility = View.VISIBLE
                                viewBinding.layoutActionBar.actionBar.visibility = View.GONE
                            } else {
                                viewBinding.layoutActionBarTranslucent.visibility = View.GONE
                                viewBinding.layoutActionBar.actionBar.visibility = View.VISIBLE
                            }
                        } else {
                            viewBinding.layoutActionBarTranslucent.visibility = View.GONE
                            viewBinding.layoutActionBar.actionBar.visibility = View.GONE
                        }
                    }
                    7 -> {
                        try {
                            titleTextColor = Color.parseColor(event.value)
                            findViewById<TextView?>(R.id.tvTitle)?.setTextColor(titleTextColor)
                            viewBinding.tvTitleTranslucent.setTextColor(titleTextColor)
                        } catch (e: Exception) {

                        }
                    }
                }

            } catch (e: Exception) {
            }

        }, AndroidSchedulers.mainThread(), this, this)

        RxBus.observe<WebRefreshEvent>().registerInBus({ event: WebRefreshEvent ->

            try {
                if (!TextUtils.isEmpty(event.key)) {
                    val javascriptInterface = webviewJavascriptInterface
                    if (javascriptInterface != null) {
                        if (TextUtils.equals(javascriptInterface.refreshKey, event.key)) {
                            isError = false
                            viewBinding.webView.reload()
                        }
                    }

                }

            } catch (e: Exception) {

            }

        }, AndroidSchedulers.mainThread(), this, this)

        viewBinding.btnErrorRefresh.setOnClickListener {
            isError = false
            viewBinding.webView.reload()
        }
        viewBinding.btnErrorBack.setOnClickListener {
            onBackPressed()
        }
        val isTranslucent = url.contains("translucent")
        // GlobalLayoutUtils(this, isTranslucent)
        if (isTranslucent) {
            initTranslucent()
        } else {
            viewBinding.layoutActionBarTranslucent.visibility = View.GONE
            viewBinding.layoutActionBar.actionBar.visibility = View.VISIBLE
        }

        val isHideActionBar = url.contains("isYsHideActionBar")
        val isYsLightStatusBar = url.contains("isYsLightStatusBar")
        if (isYsLightStatusBar) {
            StatusBarUtils.setStatusBarLightMode(mActivity)
        }
        //
        if (isHideActionBar) {
            viewBinding.layoutActionBarTranslucent.visibility = View.GONE
            viewBinding.layoutActionBar.actionBar.visibility = View.GONE
        }

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE or WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        ViewCompat.setOnApplyWindowInsetsListener(viewBinding.layoutRoot) { view, insets ->
            insets.replaceSystemWindowInsets(0, 0, 0, insets.systemWindowInsetBottom).apply {
                ViewCompat.onApplyWindowInsets(view, this)
            }
        }
    }

    override fun initData() {

    }


    override fun setTitle(title: CharSequence?) {
        super.setTitle(title)
        viewBinding.tvTitleTranslucent.setText(title)
    }


    private fun showErrorNotice() {
        try {
            if (!viewBinding.layoutErrorNotice.isShown) {
                StatusBarUtils.setStatusBarLightMode(mActivity)
                viewBinding.webView.gone()
                viewBinding.layoutErrorNotice.visible()
            }
        } catch (e: Exception) {
        }

    }

    private fun hideErrorNotice() {
        try {
            if (viewBinding.layoutErrorNotice.isShown) {
                viewBinding.layoutErrorNotice.gone()
                viewBinding.webView.visible()
            }
        } catch (e: Exception) {
        }
    }

    private fun initTranslucent() {
        StatusBarUtils.setTransparentForWindow(this)
        StatusBarUtils.clearShadowMask(window)
        val statusHeight = StatusBarUtils.getStatusHeight(mActivity)
        viewBinding.layoutErrorNotice.setPadding(0, statusHeight, 0, 0)
        viewBinding.layoutActionBarTranslucent.visibility = View.VISIBLE
        viewBinding.layoutActionBar.actionBar.visibility = View.GONE
        viewBinding.btnBackTranslucent.setOnClickListener { onBackPressed() }
        viewBinding.tvRightText.setOnClickListener {
            viewBinding.webView.loadUrl("javascript:activeIntro()")
        }
        viewBinding.btnShare.setOnClickListener {
            viewBinding.webView.loadUrl("javascript:shareLinks()")
        }
        viewBinding.webView.setOnScrollChangeListener(object : EasyWebView.OnScrollChangeListener {
            private val topImageHeight = ScreenUtils.getScreenWidth(mActivity) / 1.6995073891626 * 0.8
            //            private val backgroundColor = activity.resources.getColor(R.color.colorPrimaryBlack)

            override fun onPageEnd(l: Int, t: Int, oldl: Int, oldt: Int) {
            }

            override fun onPageTop(l: Int, t: Int, oldl: Int, oldt: Int) {
            }

            override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
                if (viewBinding.layoutActionBarTranslucent.visibility == View.VISIBLE) {
                    if (t >= topImageHeight) {
                        viewBinding.layoutActionBarTranslucent.setBackgroundColor(backgroundColor)
                        viewBinding.tvTitleTranslucent.setTextColor(titleTextColor)
                    } else {
                        val alpha = t / topImageHeight
                        val color = ColorUtils.getColorWithAlpha(alpha, backgroundColor)
                        val textColor = ColorUtils.getColorWithAlpha(alpha, titleTextColor)
                        viewBinding.layoutActionBarTranslucent.setBackgroundColor(color)
                        viewBinding.tvTitleTranslucent.setTextColor(textColor)
                    }
                }
            }
        })
    }


    override fun onBackPressed() {
        val javascriptInterface = webviewJavascriptInterface
        if (javascriptInterface != null && javascriptInterface.checkIsNeedHandleBackPressed()) {
            viewBinding.webView.loadUrl("javascript:onBackPressed(); ")
        } else {
            if (viewBinding.webView.canGoBack()) {
                isError = false
                viewBinding.webView.goBack()
            } else {
                super.onBackPressed()
            }
        }

    }

    private var isHasOnResume = false
    override fun onPause() {
        super.onPause()
        isHasOnResume = false
        viewBinding.webView.onPause()
        viewBinding.webView.pauseTimers()
        //暂停音频
        viewBinding.webView.loadUrl(
                "javascript:audioEty = document.getElementsByTagName('audio'); " +
                        "for(var i = 0;i < audioEty.length;i++){audioEty[i].pause()}"
        )
    }

    override fun onResume() {
        super.onResume()
        viewBinding.webView.onResume()
        viewBinding.webView.resumeTimers()
        //播放音频
        viewBinding.webView.loadUrl(
                "javascript:audioEty = document.getElementsByTagName('audio'); " +
                        "for(var i = 0;i < audioEty.length;i++){" +
                        "if(audioEty[i].paused){" +
                        "audioEty[i].play()}}"

        )
        isHasOnResume = true

    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (viewBinding.webView.canGoBack()) {
                isError = false
                viewBinding.webView.goBack()
                return true
            }
        }

        return super.onKeyDown(keyCode, event)


    }

    override fun onDestroy() {
        try {
            viewBinding.webView?.let {
                it.stopLoading()
                it.removeAllViewsInLayout()
                it.removeAllViews()
                it.setWebChromeClient(null)
                it.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
                CookieSyncManager.getInstance().stopSync()
                it.destroy()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            super.onDestroy()
        }
    }

    override fun jsCall(msg: String?) {

    }
}